/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elementsDefense.towers.projectils;

import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;
import com.jme3.scene.shape.Sphere;
import elementsDefense.enemies.BasicEnemy;
import elementsDefense.enemies.HealthControl;
import elementsDefense.towers.Tower;

/**
 *
 * @author Ricardo
 */
public class HomingControl extends AbstractControl{
   
    Tower source;
    BasicEnemy target;
    Projectil projectil;
    float velocity;

    public HomingControl(Tower source, BasicEnemy target, Projectil projectil, float velocity) {
        this.source = source;
        this.target = target;
        this.projectil = projectil;
        this.velocity = velocity;
    }
    
    public void reset(Tower source, BasicEnemy target, Projectil projectil, float velocity) {
        this.source = source;
        this.target = target;
        this.projectil = projectil;
        this.velocity = velocity;
        spatial.setLocalTranslation(source.fireLocation);
        setEnabled(true);
    }

    @Override
    public void setSpatial(Spatial spatial) {
        super.setSpatial(spatial);
        if(spatial!=null)
            spatial.setLocalTranslation(source.fireLocation);
    }
    
    
    
    Vector3f direction=new Vector3f();
    @Override
    protected void controlUpdate(float tpf) {
        direction.set(target.getLocation()).subtractLocal(spatial.getLocalTranslation());
        if(direction.length()<0.1f){
            projectil.hit();
            setEnabled(false);
        }else{
            direction.normalizeLocal();
            spatial.move(direction.multLocal(velocity));
        }
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
    }

    public Control cloneForSpatial(Spatial spatial) {
        final HomingControl control = new HomingControl(source, target, projectil, velocity);
        /* Optional: use setters to copy userdata into the cloned control */
        // control.setIndex(i); // example
        control.setSpatial(spatial);
        return control;
    }
    
}
